package dbutil

import (
	"github.com/jinzhu/gorm"
	"gitee.com/cjf8134/bbs_serve/internal/pkg/utils/constutil"
)

type ScopeFunc func(db *gorm.DB) *gorm.DB

func PageOrder(p map[string]int, o map[string]string) ScopeFunc {
	return func(db *gorm.DB) *gorm.DB {
		limit, ok := p["limit"]
		if !ok {
			limit = constutil.DefaultPageSize
		}
		if limit > constutil.DefaultMaxPageSize {
			limit = constutil.DefaultMaxPageSize
		}
		offset, ok := p["offset"]
		if !ok {
			offset = 0
		}
		if offset < 0 {
			offset = 0
		}
		str := ""
		field, ok := o["order"]
		if !ok || field == "" {
			return db.Offset(offset * limit).Limit(limit).Order("id desc")
		}
		b, ok := o["desc"]
		if !ok || b == "1" {
			str = field + " " + "desc"
		} else {
			str = field + " " + "asc"
		}
		return db.Offset(offset * limit).Limit(limit).Order(str)
	}
}
